<script lang="ts" setup>
import { computed, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import GoodsItem from './components/goods-item.vue'
import SubBread from './components/sub-bread.vue'
import SubFilter from './components/sub-filter.vue'
import SubSort from './components/sub-sort.vue'
import { findSubCategoryGoods } from '@/api/category'
import type { IFilterParams, IsortParams, ITemporaryItem } from '@/types/api/category'

const route = useRoute()
const loading = ref(false) // 本次加载是否完成
const finished = ref(false) // 数据是否加载完毕
const goodsList = ref<ITemporaryItem[]>([]) // 商品列表数据

// 查询参数
let reqParams = {
  page: 1,
  pageSize: 20,
  categoryId: ''
}

// 获取数据列表
const getData = () => {
  loading.value = true
  reqParams.categoryId = route.params.id as string

  findSubCategoryGoods(reqParams).then((res) => {
    const { result } = res.data
    if (result.items.length) {
      goodsList.value.push(...result.items)
      reqParams.page++
    } else {
      // 数据加载完毕
      finished.value = true
    }
    loading.value = false
  })
}

// 切换二级分类重新加载数据
watch(
  () => route.params.id,
  (newVal) => {
    if (newVal && route.path === '/category/sub/' + newVal) {
      goodsList.value = []
      // 查询参数
      reqParams = {
        page: 1,
        pageSize: 20,
        categoryId: ''
      }
      finished.value = false
      loading.value = false
    }
  }
)

// 监听排序改变
const changeSort = (sortParams: IsortParams) => {
  finished.value = !finished.value
  loading.value = !loading.value
  reqParams = { ...reqParams, ...sortParams }
  reqParams.page = 1
  goodsList.value = []
  getData()
}

const changeFilter = (filterParams: IFilterParams) => {
  finished.value = !finished.value
  loading.value = !loading.value
  reqParams = { ...reqParams, ...filterParams }
  reqParams.page = 1
  goodsList.value = []
  getData()
}
</script>

<template>
  <div class="sub-category">
    <div class="container">
      <!-- 面包屑 -->
      <SubBread />
      <!-- 筛选区 -->
      <SubFilter @filter-change="changeFilter" />
      <div class="goods-list">
        <!-- 排序 -->
        <SubSort @sort-change="changeSort" />
        <!-- 列表 -->
        <ul>
          <li v-for="item in goodsList" :key="item.id">
            <GoodsItem :goods="item" />
          </li>
        </ul>
        {{ Number(loading) }}{{ Number(finished) }}
        <XtxInfinite :loading="loading" :finished="finished" @infinite="getData" />
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.goods-list {
  background: #fff;
  padding: 0 25px;
  margin-top: 25px;
  ul {
    display: flex;
    flex-wrap: wrap;
    padding: 0 5px;
    li {
      margin-right: 20px;
      margin-bottom: 20px;
      &:nth-child(5n) {
        margin-right: 0;
      }
    }
  }
}
</style>
